package com.coolbi.security.web.action;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.coolbi.common.web.action.BaseAction;
import com.coolbi.security.biz.UserGroupBiz;
import com.coolbi.security.biz.UserToGroupBiz;
import com.coolbi.security.entity.User;
import com.coolbi.security.entity.UserGroup;

public class UserGroupAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private UserGroup userGroup;
	private List<UserGroup> userGroupList;
	private List<User> userList;

	@Autowired
	private UserGroupBiz userGroupBiz;

	public void setUserGroupBiz(UserGroupBiz userGroupBiz) {
		this.userGroupBiz = userGroupBiz;
	}

	@Autowired
	private UserToGroupBiz userToGroupBiz;

	public void setUserToGroupBiz(UserToGroupBiz userToGroupBiz) {
		this.userToGroupBiz = userToGroupBiz;
	}

	/**获取所有Group信息*/
	public String list() throws Exception {
		try {
			userGroupList = userGroupBiz.list();
			Collections.sort(userGroupList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/** 添加用户组 */
	public String addUserGroup() throws Exception {
		userGroup = userGroupBiz.save(userGroup);
		userGroupList = userGroupBiz.list();
		return SUCCESS;
	}

	/** 删除用户组 */
	public String delete() throws Exception {
		userGroupBiz.delete(userGroup.getId());
		userGroupList = userGroupBiz.list();
		return SUCCESS;
	}

	/** 修改用户组 */
	public String update() {
		try {
			userGroupBiz.update(userGroup);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	/** 根据ID获取用户组信息 */
	public String findUserGroupById() throws Exception {
		userGroup = userGroupBiz.get(userGroup.getId());
		return SUCCESS;
	}

	/** 根据用户组ID查询用户 */
	public String findUsersByGroupId() throws Exception {
		userGroup = userGroupBiz.get(userGroup.getId());
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("groupId", userGroup.getId());
		pager.setRecordCount(userToGroupBiz.count(parameter));
		userList = userToGroupBiz.findUserByGroupId(parameter, 
								(pager.getCurrPageNo() - 1) * pager.getPageSize(),
								pager.getPageSize());
		return SUCCESS;
	}

	public UserGroup getUserGroup() {
		return userGroup;
	}

	public void setUserGroup(UserGroup userGroup) {
		this.userGroup = userGroup;
	}

	public List<UserGroup> getUserGroupList() {
		return userGroupList;
	}

	public void setUserGroupList(List<UserGroup> userGroupList) {
		this.userGroupList = userGroupList;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
}
